from game.model import LLM, USER_PROMPT
import json
import re

class GameNode:
    def __init__(self, description:str, choices:list):
        self.description = description
        self.choices = choices

    def show_info(self):
        print('\n[当前局面]:')
        print(self.description)
        print('\n你有以下选择:')
        for i, choice in enumerate(self.choices):
            print(f"{i+1}: {choice}")
        print()
    
    def isEnd(self):
        return '[END]' in self.description
    
    def generate_next_node(self, story_llm:LLM, choice:int):
        "选择节点node的choice后，故事进一步发展"
        ai_input = USER_PROMPT.format(
            description = self.description,
            choices = '\n'.join(self.choices),
            user_choice = self.choices[choice-1]
        )
        response = story_llm.chat(ai_input)
        
        # 直接尝试解析JSON
        try:
            response = json.loads(response)
            next_node = GameNode(description=response['description'],
                               choices=response['choices'])
        except json.JSONDecodeError:
            # 如果还是失败，返回默认结束节点
            return GameNode(description="[END]", choices=["","",""])
            
        return next_node